"""
解析文件
"""
from har2case.core import HarParser

from .parserBase import BaseParser


class HrunParser_har(HarParser, BaseParser):
    """
    处理har文件内容
    """

    def __init__(self, oContent=None):
        super().__init__('')
        if oContent:
            self.Content = oContent
            self.content_json = self._loadContent()

    def _loadContent(self):
        try:
            import json
            content_json = json.loads(self.Content)
            return content_json["log"]["entries"]
        except (KeyError, TypeError):
            raise Exception('HAR file content error')

    def _prepare_teststeps(self, fmt_version):
        """ make teststep list.
            teststeps list are parsed from HAR log entries list.

        """

        def is_exclude(url, exclude_str):
            exclude_str_list = exclude_str.split("|")
            for exclude_str in exclude_str_list:
                if exclude_str and exclude_str in url:
                    return True

            return False

        teststeps = []
        # log_entries = utils.load_har_log_entries(self.har_file_path)
        for entry_json in self.content_json:
            url = entry_json["request"].get("url")
            if self.filter_str and self.filter_str not in url:
                continue

            if is_exclude(url, self.exclude_str):
                continue

            if fmt_version == "v1":
                teststeps.append(
                    {"test": self._prepare_teststep(entry_json)}
                )
            else:
                # v2
                teststeps.append(
                    self._prepare_teststep(entry_json)
                )

        return teststeps

    def get_HrunTestcase(self):
        file_type = "JSON"
        fmt_version = "v2"
        testcase = self._make_testcase(fmt_version)

        return testcase
